package com.example.compose.socket


import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.IOException
import java.net.InetAddress
import java.net.ServerSocket
import java.net.Socket

class Server {

    lateinit var serverSocket:ServerSocket
    private val port = 9998
    private var i = 0

    init {
        try {
            val adder = InetAddress.getLocalHost()
            println("local host:$adder")
            serverSocket = ServerSocket(port)
            println("ok")
        } catch (e:IOException) {
            e.printStackTrace()
        }
    }

    fun startService(){
        try {
            while(true){
                val socket = serverSocket.accept()
                println("connect to"+socket.inetAddress +":"+socket.localPort);
                ConnectThread(socket).start()
            }
        } catch (e:IOException) {
            e.printStackTrace();
        }

    }

    inner class ConnectThread(private val socket: Socket?) : Thread() {
        override fun run() {
            try {
                val dis = DataInputStream(socket?.getInputStream())
                val dos = DataOutputStream(socket?.getOutputStream())
                while (true) {
                    i++
                    val msgRecv: String = dis.readUTF()
                    println("msg from client:$msgRecv")
                    dos.writeUTF(msgRecv + i)
                    dos.flush()
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

    }

}